<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\OrderTemporary;
use app\common\tool\Result;
use think\Response;

class Order extends Base
{
    public function getTemporary(): Response
    {
        $temporary = OrderTemporary::getTemporary($this->user->id);
        if ($temporary['code'] != 1) {
            return Result::fail('加载失败，未查询到待提交的订单');
        }

        return Result::success('success', $temporary['data']);
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $res = OrderTemporary::submit($param, $this->user);
        if ($res['code'] === -1) {
            return Result::fail($res['msg']);
        }

        return Result::success('订单已生成', ['order_id' => $res['data']]);
    }

    public function payment($id): Response
    {
        return Result::fastReturn(OrderTemporary::getPayment($id, $this->user));
    }

    public function confirmPayment(): Response
    {
        $param = $this->request->post();
        $res = OrderTemporary::payment($param, $this->user);
        if ($res['code'] === -1) {
            return Result::fail($res['msg']);
        }

        return Result::success($res['msg']);
    }

    public function index(): Response
    {
        $param = $this->request->get();
        $map['uid'] = $this->user->id;
        if (!empty($param['status'])) {
            $map['status'] = $param['status'];
        }

        return Result::fastReturn(OrderTemporary::getPageList($map, 'id,sn,total_amount,real_amount,status,create_time',
            $this->getPage(), $this->getLimit(), false, ['productsField'], [], [], [], [], '', ['status_name']));
    }

    public function info($id): Response
    {
        $info = OrderTemporary::with(['productsField', 'p', 'c', 'd', 'express'])
            ->withoutField('freight,address_id,update_time,delete_time')
            ->where(['id' => $id, 'uid' => $this->user->id])->find();
        if (empty($info)) return Result::fail('订单不存在');
        $info->friendlyText = getProductOrderFriendly($info->status);
        $p = $info->p ? $info->p->title : '';
        $c = $info->c ? $info->c->title : '';
        $d = $info->d ? $info->d->title : '';
        $info->address = $p . $c . $d . $info->address_details;
        $info->expressInfo = $info->express ?: '';
        unset($info->p, $info->c, $info->d, $info->province, $info->city, $info->district, $info->town, $info->address_details, $info->express);

        return Result::success('success', $info);
    }

    public function edit(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(OrderTemporary::edit($param, $this->user));
    }
}